<template>
  <el-form
    ref="ruleForm"
    :model="ruleForm"
    :rules="rules"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="分类名称" prop="name" style="padding-top:10px">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="分类描述" prop="desc" style="padding-top:10px">
      <el-input v-model="ruleForm.desc" />
    </el-form-item>
    <!-- action表示要上传的地址 -->
    <el-form-item label="商品描述" prop="desc" style="padding-top:10px">
      <el-upload
        name="file"
        class="avatar-uploader"
        action="http://localhost:1337/api/v1/common/upload_file"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl | imgUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  addProducts,
  oneData,
  modifyProducts
} from '../../api/products-category.js'
export default {
  data() {
    return {
      ruleForm: {
        name: '',
        desc: ''
      },
      imageUrl: '',
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        desc: [{ required: true, message: '请填写商品描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    oneData(this.$route.query.id ? this.$route.query.id : '').then(res => {
      this.ruleForm.name = res.name
      this.ruleForm.desc = res.desc
      this.imageUrl = res.coverImage
    })
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.$route.query.id) {
            await modifyProducts(this.$route.query.id, {
              ...this.ruleForm,
              coverImage: this.imageUrl
            })
            this.$message.success('修改成功！')
            this.$router.push({
              name: 'CategoryList'
            })
          } else {
            await addProducts({
              ...this.ruleForm,
              coverImage: this.imageUrl
            })
            this.$message.success('添加成功！')
            this.$router.push({
              name: 'CategoryList'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data
    }
  }
}
</script>
